{% macro selectinput(name, values, value='') -%}
    <select class="form-control" name="{{ name }}" id="{{ name }}">
    {% for v in values %}
        <option value="{{ v }}"  {{ 'selected' if value==v }}>{{ v }}</option>
    {% endfor %}
    </select>
{%- endmacro %}
{% macro selectinputtuple(name, values, value='') -%}
    <select class="form-control" name="{{ name }}" id="{{ name }}">
    {% for v in values %}
        <option value="{{ v[0] }}"  {{ 'selected' if value==v[0] }}>{{ v[1] }}</option>
    {% endfor %}
    </select>
{%- endmacro %}

{% macro checkboxinput(name, checkedvalue, value='',extra='') -%}
    <input type="checkbox" name="{{ name }}" id="{{ name }}" value="{{ checkedvalue }}"  {{ 'checked' if value==checkedvalue }} {{ extra|safe }}>
{%- endmacro %}

{% extends "layout.html" %}
{% block headcenter %}
    <script src="/static/jquerycontextmenu/jquery.ui.position.min.js" type="text/javascript"></script>
    <script src="/static/jquerycontextmenu/jquery.contextMenu.min.js" type="text/javascript"></script>
     <link href="/static/jquerycontextmenu/jquery.contextMenu.css" rel="stylesheet" type="text/css" />
    <script src="/static/jquery.datetimepicker.full.min.js" type="text/javascript"></script>
     <link href="/static/jquery.datetimepicker.min.css" rel="stylesheet" type="text/css" />

{% if g.headmenu %}
    <table width="100%"><tr><td style="white-space: nowrap;width: 170px;">
    <div class="btn-group" style="margin-right: 5px">
    <button type="button" class="btn btn-default" data-toggle="dropdown" style="padding: 6px;">项目</button>
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false"  style="padding: 6px;">
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu dropdown-menu-left" role="menu">
      {%   for m in g.headmenu %}
          {% if m[1]=="SEP"%}
            <li class="divider"></li>
          {% else %}
            <li><a href="{{ m[0] }}">{{ m[1] }}</a></li>
          {% endif %}
      {%  endfor %}
  </ul>
</div>
    <div class="btn-group" style="margin-right: 5px">
    <button type="button" class="btn btn-default" data-toggle="dropdown"  style="padding: 6px;">筛选</button>
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false"  style="padding: 6px;">
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu dropdown-menu-left" role="menu">
      {%   for m in g.headmenuF %}
          {% if m[1]=="SEP"%}
            <li class="divider"></li>
          {% else %}
            <li><a href="{{ m[0] }}">{{ m[1] }}</a></li>
          {% endif %}
      {%  endfor %}
  </ul>
</div>

    </td><td><div id="titlediv">
      <div id=titledivtitle style="font-size: 18px;max-width: 300px;white-space: nowrap; text-overflow: ellipsis; overflow: hidden; vertical-align: bottom;display: inline-block;">{{ g.ProjectTitle }}</div>
      <div style="font-size: 12px;vertical-align: bottom;display: inline-block;"> (<span id=objcount></span>)</div></div>
    <div id="projectProgress" class="progress" style="    height: 6px;    margin-bottom: 0;    margin-top: 1px;">
				  <div id="progress-bar-validated" class="progress-bar" style="width: 0;background-color: #5CB85C;"></div>
				  <div id="progress-bar-predicted" class="progress-bar" style="width: 0;background-color: #5bc0de;"></div>
				  <div id="progress-bar-dubious" class="progress-bar" style="width: 0;background-color: #F0AD4E;"></div>
		</div>
    <div id="headersubtitle" style="color:#FF6600;overflow-y: auto;height: 42px;"> </div>

    </td></tr></table>
{% endif %} {# If headmenu #}

{% endblock %}

{% block body %}<div id="topbar" >
<input type="hidden" id="projid" value="{{ g.Projid }}">
<input type="hidden" id="taxofilter" value=""  autocomplete="off">
<input type="hidden" id="taxofilterlabel" value=""  autocomplete="off">
<input type="hidden" id="taxofilterchild" value=""  autocomplete="off">
<input type="hidden" id="pageoffset" value="{{ data.pageoffset }}"  autocomplete="off">
<table><tr><td>
    <button type="button" class="btn btn-xs btn-primary" onclick="LoadRightPane();" style="width: 260px;">
        <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> 页面刷新</button>
{{ top|safe }}
</td><td>
    &nbsp;
    <span class="btn btn-xs SpanSelectAll rm5" title="CTRL+A shortcut to select all. Hold shift key to unselect all">选择所有</span>

    <span class="glyphicon glyphicon-sort rm5"></span>
</td><td>
    <select name="sortby" id="sortby" style="width: 100px" class="form-control rm5">

{% for key, value in data.sortlist.items() %}
    <option value="{{ key|e }}" {{ 'selected' if key==data.sortby }}> {{ value|e }}</option>
{% endfor %}
</select>
</td><td>
<button type="button" class="btn btn-default btn-xs rm5" onclick="SortToggle();" title="Current Sort : Ascending">
        <span id="sortorder" class="glyphicon glyphicon-sort-by-attributes" aria-hidden="true"></span></button>

<div class="btn-group rm5">
  <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    显示 &nbsp;<span class="caret"></span>
    <span class="sr-only">Toggle Dropdown</span>
  </button>
  <ul id="dispfieldlist" class="dropdown-menu">
{% for key, value in data.fieldlist.items() %}
    <li id="dispfield_{{ key }}"  > <a href="javascript:ToggleDispField('dispfield_{{ key }}');">
        {{ value|e }} <span class="glyphicon {{ 'glyphicon-ok' if key in data.dispfield }}"></span></a></li>
{% endfor %}
  </ul>
</div>
</td> {% if not g.PublicViewMode %}
  <td >
          <label for="statusfilter" data-toggle="tooltip" data-placement="bottom" data-html="true" class="rm5" style="margin-bottom: 0;"
        title="
        <p style='text-align: left'>
        <b>All</b>: all images</br>
        <b>Unvalidated</b>: all images to validate (unclassified, predicted only and dubious)</br>
        <b>Predicted</b>: predicted by automatic classification</br>
        <b>Unclassified</b>: unpredicted and unvalidated</br>
        <b>Validated</b>: images with a human-made identification</br>
        <b>Valid. by others</b>: identification done by other users</br>
        <b>Valid. by me</b>: identification done by me</br>
        <b>Dubious</b>: dubious identification</div>">
      状态 </label></td><td style="padding-right: 5px;" class="rm5">
      <select name="statusfilter" id="statusfilter"  class="form-control" data-original-title="" title="" style="width: 100px">
{% for key, value in data.statuslist.items() %}
    <option value="{{ key|e }}" {{ 'selected' if key==data.statusfilter }}> {{ value|e }}</option>
{% endfor %}
</select></td>
  {% else %}
  <td>
  <input type="hidden" name="statusfilter" id="statusfilter" value="">
  Status : Validated Only&nbsp;
  </td>
{% endif %}
  <td style="padding-right: 5px;">
    <label for="ipp" style="margin-bottom: 0;"><span class="glyphicon glyphicon-th"></span></label>
    </td><td style="padding-right: 5px;">{{ selectinputtuple("ipp",[('0','最适'),('1','1'),('5','5'),('10','10'),('20','20'),('50','50'),('100','100'),('200','200'),('500','500'),('1000','1000')],data.ipp) }}
    </td><td style="padding-right: 5px;">    <label for="zoom" style="margin-bottom: 0;"><span class="glyphicon glyphicon-zoom-in"></span>%</label>
    </td><td style="padding-right: 5px;">{{ selectinput("zoom",['10','20','30','40','50','60','70','80','90','100','200'],data.zoom) }}</td><td>
</td><td>
      <label for="magenabled" style="margin-bottom: 0;">
      	<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
      </label>
      {{ checkboxinput("magenabled","1",data.magenabled,"style='margin:0px;'") }}
    </td><td>
      <label for="popupenabled" style="margin-bottom: 0;padding-left: 8px;">
        <span class="glyphicon glyphicon-comment" aria-hidden="true"></span>
      </label>
      {{ checkboxinput("popupenabled","1",data.popupenabled,"style='margin:0px;'") }}
    </td><td>&nbsp;
    <button type=button class="btn btn-primary btn-xs" onclick="LoadRightPane();">
      <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>
    </button>
    <span id='PendingChanges2' class='text-danger'></span>
    </td><td><span id="nbrselected" style="margin-left: 10px;"></span>&nbsp;
</td>
</tr>
</table>
    </div>
{% include "common/taxopopup.html" %}

	<div id="bodycontainer">
		<div id="column-left"  class="panelzzz " style="position: fixed;	top: 120px;	bottom: 0;	width: 260px;
	                overflow-y: hidden; overflow-x: hidden;margin-bottom: 0;" >
      <div class="bodyleft" style="margin-left: 2px; width: 257px;">
        <script>
        $(document).ready(function () {
          $('#myTabs .nav-tabs a').click(function (e) {
            e.preventDefault();
            $(this).tab('show');
          });

          $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            if($(e.target).attr('href')=='#TabB') {# Doit être fait dans le changement de tab car au debut l'onglet n'est pas visible et le calcul est faut #}
                $("#TabB").outerHeight( $("#column-left").innerHeight()-$("#TabB").position().top);
            });
        }); {# ready #}
function DispClassificationHelp(projid){
  $("#PopupDetails .modal-content").load("/static/taxofilterhelp_20190128.html");
  $('#PopupDetails').modal({});
}


        </script>
          <div id="myTabs">  <!-- Nav tabs -->
            <ul class="nav nav-tabs nav-justified" role="tablist">
              <li role="presentation" class="active">
                  <a href="#TabA" aria-controls="home" role="tab" data-toggle="tab">分类过滤器
                  <!-- <span title="Taxo filter help" class="glyphicon glyphicon-info-sign" style="color: black" onclick="DispClassificationHelp()"></span> -->
                  </a>

              </li>
              <li role="presentation">
                  <a href="#TabB" aria-controls="profile" role="tab" data-toggle="tab">其他过滤器</a>
              </li>
            </ul>
            <div class="tab-content"> <!-- Tab panes -->
              {# Classification #}
              <div role="tabpanel" class="tab-pane active" id="TabA">
                  {{ lefta|safe }}
              </div>
              {# Filters #}
              <div role="tabpanel" class="tab-pane" id="TabB" style="overflow-y: auto;overflow-x: hidden;">
                  <div id="TabBInner" style="width: 240px;">
                     <button class="btn btn-info" style="width: 49%" id=SharePageBtn title="Email a link to this page, including the current filters. Press CTRL to open it on another tab (usefull if you use GMail)"><span class="glyphicon glyphicon-link"></span> 分享页面</button>
                     <button onclick='ClearAllFilterCriteria();return false;' class="btn btn-info" style="width: 49%" title="Remove all selection criteria"><span class="glyphicon glyphicon-remove" ></span> 清除所有过滤条件</button>
                  <br>
                  {{ leftb|safe }}
{# ------- Annotator / Freefilter ------------#}
<div class="filter ">
	<div class="form-group-sm">
		<label class="title">注释者/免费过滤器</label>
		<a class="pull-right label label-default" style="padding: 1px 3px 3px 3px; margin-top: 5px;font-size: 90%;" href=# onclick='ClearAnnotFree();return false;'>清除</a>
		<a class="pull-right label label-info" style="padding: 1px 3px 3px 3px; margin-top: 5px;font-size: 90%;margin-right: 5px;" href=# onclick='AdvancedAnnot();return false;'>高级选项</a>
    <select class="form-control" id="filt_annot" name="filt_annot" style="width: 100%" multiple autocomplete="off">{{ data.filt_annot_for_select|safe }}</select>
	</div>
</div>
<div>
<input class="form-control" type="text" style="width: 100%" id="filt_validfromdate" name="filt_validfromdate" value="" autocomplete="off" placeholder="验证日期起始">
<input class="form-control" type="text" style="width: 100%" id="filt_validtodate" name="filt_validtodate" value="" autocomplete="off" placeholder="验证日期终止">
</div>
<form class="form-inline">
  <select class="form-control" id="filt_freenum" name="filt_freenum" style="width: 49%" autocomplete="off">
      {{ data.filt_freenum_for_select|safe }}
  </select>
  <input class="form-control" type="text" style="width: 24%" id="filt_freenumst" name="filt_freenumst" value="{{ data.freenumst }}" autocomplete="off" placeholder=">=">
  <input class="form-control" type="text" style="width: 24%" id="filt_freenumend" name="filt_freenumend" value="{{ data.freenumend }}" autocomplete="off" placeholder="<=">
</form>
<form class="form-inline">
  <select class="form-control" id="filt_freetxt" name="filt_freetxt" style="width: 59%" autocomplete="off">
      {{ data.filt_freetxt_for_select|safe }}
  </select>
  <input class="form-control" type="text" style="width: 39%" id="filt_freetxtval" name="filt_freetxtval" value="{{ data.freetxtval }}" autocomplete="off" placeholder="包含">
</form>
    <div class="row">
      <div class="col-sm-12">
            <button type="button" class="btn btn-xs btn-primary  btn-block" onclick="LoadRightPane();" >
        <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span> 页面刷新</button>
         <button class="btn btn-xs btn-info btn-block" onclick="LoadRightPane(false,true);" title="Save current settings for the filters, in this project">保存筛选条件</button>
         <a href='?' type="button" class="btn btn-xs btn-info btn-block" title="Load saved filter criteria and reload the page">应用保存的过滤条件和更新视图</a>
      </div>
    </div>
           </div>
        </div>
       </div>
      </div>
     </div>
		</div>
{#          <div id="column-right" style="position: absolute;top: 150px;left: 270px;bottom: 0px;right: 1px;overflow: auto;"> #}
<style>
.lazy {margin: 15px 5px 0 5px; cursor: -webkit-grab; cursor:grab;}
.ddet {text-align:left;  font-size: 10px; margin-top: -3px;margin-bottom: -1px;  text-decoration: underline; color:#00c;}
.ddets {cursor:pointer;}
.categexpander {cursor:pointer;}
.taxo {cursor: -webkit-grab; cursor:grab;}
#dispfieldlist li a {    padding-top:0;}
.ui-selected { background-color: #E9D6D7;}

#column-right {margin-left: 260px;}
#divheadinfo {position:fixed;top:0;left: 1px;width:100%; height:80px;z-index:12; background-color: #fff;min-width: 1024px;}
#topbar {position:fixed;top:80px;left: 1px;width:100%; height:40px;z-index:10; background-color: #fff;}
body {margin-top: 125px;}
{#Permet de fixer la largeur de la dropdown Taxo Annotation#}
.width240{ width: 240px !important; }
{#Permet de fixer la largeur de la dropdown Sample#}
.width400{ width: 400px !important; }
{#Permet de reduire la taille et l'espace du texte du dropdown Taxo Annotation#}
#select2-taxolbanno-results li {font-size: 12px; padding: 3px;}
.popover {max-width: 500px;}
#headersubtitle .btn-gris {padding-top: 0;padding-bottom: 0;border:0;}
#headersubtitle .btn-gris div:nth-child(1){max-width:500px;text-overflow: ellipsis; overflow: hidden;display: inline-block;vertical-align: bottom;}
</style>
<script>
var PendingChanges={};
var PendingChangesTaxoName={};
var PrevTxtFilter="INITIAL";
var RightPanelScrollPosAfterLoad=0;
DragInProgress=false;
function InGreyButton(s,eraser) {
  return " <button type=button class='btn btn-gris btn-xs' onclick='"+eraser+";LoadRightPane();'><div>"+s+"</div> <span class='glyphicon glyphicon-remove'></span></button>";
}
$('#SharePageBtn').click(function (e) {
  if(e.ctrlKey)
    LoadRightPane('mailN');
  else
    LoadRightPane('mail');
});
function LoadRightPane(NoAjax,SaveInProfile){
    document.activeElement.blur();
    if(Object.keys(PendingChanges).length>0)
      if(confirm("Some changes are pending, if you continue they will be discarded !\n\nWould you still like to continue ?")==false)
        return;
    var TxtFilter="",jqtaxofilter=$("#taxofilter"),jqtaxofilterlbl=$("#taxofilterlabel"),jqcolumnright=$("#column-right");
    var req={taxo:jqtaxofilter.val(),resultwidth:jqcolumnright.width(),windowheight:$(window).height()};
    if(jqtaxofilterlbl.val()!="")
        TxtFilter+=InGreyButton("Taxo="+jqtaxofilterlbl.val(),"SetTaxoFilter(false)");
    $(".activeTaxo").removeClass("activeTaxo");
    if(jqtaxofilter.val()!="")
        $("#TabA").find("[data-taxoid="+jqtaxofilter.val()+"]").addClass("activeTaxo");
    req['taxochild']=$("#taxofilterchild").val();
    req['ipp']=$("#ipp").val();
    req['zoom']=$("#zoom").val();
    req['sortby']=$("#sortby").val();
    req['magenabled']=$("#magenabled").prop("checked")?"1":"0";
    req['popupenabled']=$("#popupenabled").prop("checked")?"1":"0";
    var jqstatusfilter=$("#statusfilter");
    req['statusfilter']=jqstatusfilter.val();
    if(jqstatusfilter.val()!="")
        TxtFilter+=InGreyButton("Status="+jqstatusfilter.find("option:selected").text(),"$(\"#statusfilter\").val(null)");
    req['MapN']=$("#filt_MapOutN").val();
    req['MapW']=$("#filt_MapOutW").val();
    req['MapE']=$("#filt_MapOutE").val();
    req['MapS']=$("#filt_MapOutS").val();
    if((req['MapN']!="")&&(req['MapW']!="")&&(req['MapE']!="")&&(req['MapS']!=""))
        TxtFilter+=InGreyButton(" Position=("+req['MapN']+","+req['MapW']+","+req['MapE']+","+req['MapS']+")","ClearCoord()");
    else {delete req['MapN']; delete req['MapW'];delete req['MapE']; delete req['MapS']; }

    req['depthmin']=$("#filt_depthmin").val();
    req['depthmax']=$("#filt_depthmax").val();
    if((req['depthmin']!="")&&(req['depthmax']!=""))
        TxtFilter+=InGreyButton(" Depth in("+req['depthmin']+"-"+req['depthmax']+")","ClearDepths()");
    else {delete req['depthmin']; delete req['depthmax']; }
    var jqfreenum=$("#filt_freenum");
    req['freenum']=jqfreenum.val();
    req['freenumst']=$("#filt_freenumst").val();
    req['freenumend']=$("#filt_freenumend").val();
    if((req['freenum']!="")&&((req['freenumst']!="")||(req['freenumend']!="")))
        TxtFilter+=InGreyButton(jqfreenum.find("option:selected").text()+" in("+req['freenumst']+"-"+req['freenumend']+")"
                       ,"$(\"#filt_freenum,#filt_freenumst,#filt_freenumend\").val(null).trigger(\"change\")");
    else {delete req['freenum']; delete req['freenumst'];delete req['freenumend']; }
    var jqfreetxt=$("#filt_freetxt");
    req['freetxt']=jqfreetxt.val();
    req['freetxtval']=$("#filt_freetxtval").val();
    if((req['freetxt']!="")&&(req['freetxtval']!=""))
        TxtFilter+=InGreyButton(jqfreetxt.find("option:selected").text()+" contains "+req['freetxtval']
                      ,"$(\"#filt_freetxt,#filt_freetxtval\").val(null).trigger(\"change\")");
    else {delete req['freetxt']; delete req['freetxtval']; }

    var sampleid=$('#sampleid');
    if(sampleid.val()!=null)
      req['samples']=String(sampleid.val());
    else req['samples']="";
    if(req['samples']!="")
        TxtFilter+=InGreyButton("Samples="+$.map(sampleid.find('option:selected'), function (element) { return $(element).text() }).join(', '),"ClearSamples()");
    req['instrum']=$("#filt_instrum").val();
    if(req['instrum']!="")
        TxtFilter+=InGreyButton("Instrument ="+req['instrum'],"ClearInstrum()");
    var jqmonth=$('#month');
    if(jqmonth.val()!=null) {
      req['month'] = String(jqmonth.val());
      TxtFilter += InGreyButton("Month=" + $.map(jqmonth.find('option:selected'), function (element) {
            return $(element).text()
          }).join(', '),"ClearDates()");
    }
    var jqannot=$('#filt_annot');
    if(jqannot.val()!=null) {
      req['filt_annot'] = String(jqannot.val());
      TxtFilter += InGreyButton("Annotateur=" + $.map(jqannot.find('option:selected'), function (element) {
            return $(element).text()
          }).join(', '),"$(\"#filt_annot\").val(null).trigger(\"change\")");
    }
    req['fromdate']=$("#filt_fromdate").val();
    if(req['fromdate']!="")
        TxtFilter+=InGreyButton("Date &ge; "+req['fromdate'],"ClearDates()");
    else delete req['fromdate'];
    req['todate']=$("#filt_todate").val();
    if(req['todate']!="")
        TxtFilter+=InGreyButton("Date &le; "+req['todate'],"ClearDates()");
    else delete req['todate'];

    req['fromtime']=$("#filt_fromtime").val();
    req['totime']=$("#filt_totime").val();
    if((req['fromtime']!="")&&(req['totime']!=""))
      TxtFilter+=InGreyButton("Time &ge; "+req['fromtime']+",&le;"+req['totime'],"ClearTimes()");
  else {
      if (req['fromtime'] != "")
        TxtFilter += InGreyButton("Time &ge; " + req['fromtime'], "ClearTimes()");
      else delete req['fromtime'];
      if (req['totime'] != "")
        TxtFilter += InGreyButton("Time &le; " + req['totime'], "ClearTimes()");
      else delete req['totime'];
    }
    req['inverttime']=$("#filt_inverttime").prop("checked")?"1":"";
    if(req['inverttime']=="1")
        TxtFilter+=InGreyButton("Time Invert","$(\"#filt_inverttime\").prop(\"checked\",false)");
    else delete req['inverttime'];
    var jqdaytime=$('#daytime');
    if(jqdaytime.val()!=null) {
      req['daytime'] = String(jqdaytime.val());
      TxtFilter+=InGreyButton("DayTime="+$.map(jqdaytime.find('option:selected'), function (element) { return $(element).text() }).join(', '), "ClearTimes()");
    }

    req['validfromdate']=$("#filt_validfromdate").val();
    if(req['validfromdate']!="")
        TxtFilter+=InGreyButton("Valid date &ge; "+req['validfromdate'],'$(\"#filt_validfromdate\").val(\"\")');
    else delete req['validfromdate'];
    req['validtodate']=$("#filt_validtodate").val();
    if(req['validtodate']!="")
        TxtFilter+=InGreyButton("Valid date &le; "+req['validtodate'],'$(\"#filt_validtodate\").val(\"\")');
    else delete req['validtodate'];


    req['sortorder']=$('#sortorder').hasClass("glyphicon-sort-by-attributes-alt")?"desc":'asc';
    req['dispfield']="";
    $("#dispfieldlist").find(".glyphicon-ok").closest("li").each(function () {
        req['dispfield'] += " " + $(this).prop("id");
    });
    req['projid']=$("#projid").val();
    $(".zoomtracker,.zoomstatus,.magnifyarea,.cursorshade").remove();
    PendingChanges={}; {# After load there's no pending changes #}
    PendingChangesTaxoName={};
    if(TxtFilter!="")
        TxtFilter="Filter: "+TxtFilter;
    var jqpageoffset=$("#pageoffset");
    if(TxtFilter!=PrevTxtFilter) { {# Si une condition change on revient page 1 #}
        if(PrevTxtFilter!="INITIAL") // Mais pas sur le premier load de page qui peut être avec une URL qui met un filtre
            jqpageoffset.val(0);
        PrevTxtFilter=TxtFilter;
    }
    req['pageoffset']=jqpageoffset.val();
    var urlparam={},url,k;
    if((NoAjax==='mail')||(NoAjax==='mailN')) {
        delete req["resultwidth"];
        delete req["windowheight"];
        for	(k in req)
            urlparam[k]=req[k];
        url=window.location.protocol+"//"+window.location.host+window.location.pathname+"?"+$.param(urlparam);
        url="mailto:?subject=Ecotaxa%20page%20share&body="+encodeURIComponent("Hello,\n\nAn Ecotaxa user want share this page with you \n"+url);
        if(NoAjax==='mail')
          window.location=url;
        else
          window.open(url,'_blank');
        return;
    }
    if(typeof (NoAjax)==='string') { {# Une URL #}
      delete req["resultwidth"];
      delete req["windowheight"];
      for	(k in req)
          if(req[k]!=="")
              urlparam[k]=req[k];
      url=NoAjax;
      if(url.indexOf('?')>0) url+="&";
      else url+="?";
      url+=$.param(urlparam);
      window.location=url;
      return;
    }
    if(SaveInProfile==true)
        req["saveinprofile"]='Y';
    jqcolumnright.html("<img src='/static/spinningred.gif'> Loading");
    jqcolumnright.load("/prj/LoadRightPane",req);
    $('#headersubtitle').html(TxtFilter);
}

function RefreshClassifTab(ForceRecalc)
{
  var jOptionSelected=$('#taxolbanno option:selected');
  Restoretaxolbid=jOptionSelected.val();
  Restoretaxolbtxt=jOptionSelected.text();
  Restoretaxolb=$('#taxolbanno option').detach();
  RestoreHighLigthID=$('.ui-droppable.ui-state-highlight').data('taxoid');
  RestoreActiveTaxoID=$('.ui-droppable.activeTaxo').data('taxoid');
  var HiddenItems=$('.classiftab td').filter(function() { return $(this).css('display') == 'none';}).map(function() { return $(this).data('taxoid'); }).get();
    var HorizArrow=$('.classiftab td span.glyphicon-triangle-right').closest('td').map(function() { return $(this).data('taxoid'); }).get();
    var PosScrollBar=$('#divclassiftab').scrollTop();
    var req={taxo:$("#taxofilter").val(),taxofilterlabel:$("#taxofilterlabel").val()};
    if(ForceRecalc==='Y') req['ForceRecalc']='Y';
    $("#TabA").load("/prjGetClassifTab/"+$("#projid").val(),req,function() {
        $.each(HiddenItems, function (k, v) { {# Masque ceux qui etaient déjà cachés #}
            $('.classiftab td[data-taxoid=' + v + ']').css('display', 'none');
        });
        $.each(HorizArrow, function (k, v) { {# Masque ceux qui etaient déjà cachés #}
            $('.classiftab td[data-taxoid=' + v + '] span.glyphicon-triangle-bottom').removeClass("glyphicon-triangle-bottom").addClass("glyphicon-triangle-right");
        });
        $('#divclassiftab').scrollTop(PosScrollBar);
    });

}

function SortToggle(NoRefresh) {
  if($('#sortorder').hasClass("glyphicon-sort-by-attributes"))
       $('#sortorder').removeClass("glyphicon-sort-by-attributes").addClass("glyphicon-sort-by-attributes-alt").closest('button').prop("title","Current Sort : Descending");
  else $('#sortorder').removeClass("glyphicon-sort-by-attributes-alt").addClass("glyphicon-sort-by-attributes").closest('button').prop("title","Current Sort : Ascending");
  if(NoRefresh!=='NoRefresh') {
    $("#pageoffset").val(0);    {# Force le retour à la premiere page #}
    LoadRightPane();    {# 20181024 Autorefresh #}
  }
}

function ToggleDispField(caller){
    $('#'+caller).find('span').toggleClass("glyphicon-ok");
    $('#'+caller).find('span').removeClass("ManualAdd");
    $('#'+caller).find('span.glyphicon-ok').addClass("ManualAdd");
    LoadRightPane();{# 20181024 Autorefresh #}
    //return false;
}
function gotopage(nopage)
{
    $("#pageoffset").val(nopage);
    LoadRightPane();
}

$(document).ready(function() {
    if ("{{data.sortorder}}"=="desc")    //TOCHECK LN
        SortToggle('NoRefresh');
    $('[data-toggle="tooltip"]').tooltip();
    $("#titledivtitle").css("max-width",$("#titlediv").parent().width()-150);
    {% if g.taxofilter %}
    SetTaxoFilter({{ g.taxofilter }},"{{ g.taxofilterlabel }}"{{ ",true" if g.taxochild=='Y' }});
    {% endif %}

    var PreviousSort=$('#sortby').val();
{#Si on choisi un champ pour le tri, ca l'ajoute automatiquement dans les displayed fields#}
    $('#sortby').change(function(){
        $("#dispfield_"+PreviousSort+"  .glyphicon:not(.ManualAdd)").removeClass('glyphicon-ok');
        $("#dispfield_"+$(this).val()+" .glyphicon").addClass('glyphicon-ok');
        PreviousSort=$(this).val();
        $("#pageoffset").val(0); {# Changement d'ordre on revient à la première page #}
        LoadRightPane();{# 20181024 Autorefresh #}
    });
    $('#statusfilter,#ipp,#zoom,#magenabled,#popupenabled').change(function () {LoadRightPane();}); {# 20181024 Autorefresh #}
    {#  Plus stylé sous FFX mais plus de ressource et la dropdown est moins compacte
    $('#sortby').select2({minimumResultsForSearch: Infinity,dropdownAutoWidth : true});
    $('#ipp').select2({minimumResultsForSearch: Infinity,dropdownAutoWidth : true});
    $('#zoom').select2({minimumResultsForSearch: Infinity,dropdownAutoWidth : true});
     #}

    $("#filt_annot").select2({
        ajax: {
            url: "/search/users",
            dataType: 'json',
            delay: 250,
            data: function (params) {  return { q: params.term, page: params.page };  },
            processResults: function (data, page) { return { results: data};  },
            cache: true
        },
        minimumInputLength: 2
      ,placeholder: "注释者"
    }); // Select2 Ajax
    $("#filt_freenum").select2({
        ajax: {
            url: "/prj/GetFieldList/{{ g.Projid }}/n",
            dataType: 'json',
            delay: 250,
            data: function (params) {  return { q: params.term, page: params.page };  },
            processResults: function (data, page) { return { results: data};  },
            cache: true
        },placeholder: "数域",dropdownCssClass:"width240"});
    $("#filt_freetxt").select2({
        ajax: {
            url: "/prj/GetFieldList/{{ g.Projid }}/t",
            dataType: 'json',
            delay: 250,
            data: function (params) {  return { q: params.term, page: params.page };  },
            processResults: function (data, page) { return { results: data};  },
            cache: true
        },placeholder: "文本域",dropdownCssClass:"width240"});

{#     Ctrl + A affecte la valeur selectionnée#}
{#    $('#taxolbanno').closest('.input-group').find('.select2-selection--single').bind('keydown', 'Test1', function(e) {#}
    $(document).bind('keydown', 'Test1', function(e) {
       if((e.keyCode === 65)&& (e.ctrlKey||e.metaKey)) { {# CTRL+A #}
          SelectAll(e);
          e.preventDefault();
      }
       if((e.keyCode === 68)&& (e.ctrlKey||e.metaKey)) { {# CTRL+D #}
          AssignTaxoLbToSelection();
          e.preventDefault();
      }
       if((e.keyCode === 76)&& (e.ctrlKey||e.metaKey)) { {# CTRL+L #}
          ValidateSelection('V');
          e.preventDefault();
      }
       if((e.keyCode === 83)&& (e.ctrlKey||e.metaKey)) { {# CTRL+S #}
{#          console.log(e);#}
          SavePendingChanges();
          e.preventDefault();
      }

    });
{#  Si pression sur une touche alors que le focus n'est sur aucun input (donc dans body), on ouvle la popup#}
    $(document).bind('keydown', function(e) {
      if((document.activeElement.nodeName=='BODY')||(document.activeElement.nodeName=='SPAN'))
       if((e.keyCode >= 65)&&(e.keyCode <= 90)&& !e.ctrlKey&& !e.metaKey)
         if($(".ui-selected").length>0)
       {
         $('#taxolbanno').select2("open");
         $('.taxopopup .select2-search__field').val(String.fromCharCode(e.keyCode));
          //console.log(e);
          e.preventDefault();
      }
    });
  $('#filt_validfromdate,#filt_validtodate').datetimepicker({format:'Y-m-d H:i'});
});
function UpdateSelectedCounter() {
  var nbr=$("#column-right td.ui-selected").size();
  if (nbr>0) nbr=nbr+" Selected";
  else nbr="";
  $('#nbrselected').text(nbr);
}
function PostAddImages(){
        $(document).scrollTop(0);
        // Required to  have Select2 component working on Bootstrap Popup
        $.fn.modal.Constructor.prototype.enforceFocus = function() {};
        // Add Zoom
        jQuery('div#column-right img.lazy').Lazy({bind: 'event',afterLoad: function(element) {
            if($('#magenabled').prop("checked")==false)
                return; // Si il y a une checkbox magenabled et qu'elle est decochée on ne met pas le zoom
            AddZoom(element);}});
        // Make sub image draggable
        jQuery('.imgtab td').draggable({revert:true,revertDuration:0,cursor: "move",refreshPositions:true,
      	    cursorAt: { top: 0, left: 0 },
            start: function( event, ui ) { DragInProgress=true;},
            stop: function( event, ui ) { DragInProgress=false;},
			helper: function( ev ) {return $( "<img src='/static/drag_cursor.png'>" );}   });
{#        jQuery('.imgtab td img').draggable({revert:true,revertDuration:0});#}
        // Make the cell clickable for selection
        jQuery('.imgtab td').click(function(e){
            if($(e.target).hasClass('linestart')) {
                var nbrselectedinline=$(e.target).closest('tr').find('td.ui-selected').size();
                if ((e.shiftKey)||(nbrselectedinline>0)) { // Unselect line
                    $(e.target).closest('tr').find('td').removeClass('ui-selected');
                    if (window.getSelection) {
                      if (window.getSelection().empty) {  // Chrome
                        window.getSelection().empty();
                      } else if (window.getSelection().removeAllRanges) {  // Firefox
                        window.getSelection().removeAllRanges();
                      }
                    } else if (document.selection) {  // IE?
                      document.selection.empty();
                    }
                  UpdateSelectedCounter();
                  return;
                } }
            if ((e.ctrlKey)||(e.metaKey)) {#  20161018 on inverse la logique CTRL permet de ne PAS faire de selection multiple #}
                $('.ui-selected').removeClass('ui-selected');
            if($(e.target).hasClass('linestart')) // select line (except this first column)
                $(e.target).closest('tr').find('td:nth-child(1n+2)').addClass('ui-selected');
            else
              $(e.target).closest('td').toggleClass('ui-selected');
            UpdateSelectedCounter()
            });
        // Make ZoomTracker Clickable for selection
        jQuery('body').delegate('.zoomtracker','click',function(e){
            {# if ((!e.ctrlKey)&&(!e.metaKey))   20161018 on inverse la logique CTRL permet de ne PAS faire de selection multiple#}
            if ((e.ctrlKey)||(e.metaKey))
                $('.ui-selected').toggleClass('ui-selected');
            $($(e.target).data("specs").origImg.parents("td")[0]).toggleClass('ui-selected');
            UpdateSelectedCounter();
            });
        // setup zoomtracker creation tracking to make them draggable
        var target = $( "body" )[0];
        var observer = new MutationObserver(function( mutations ) {
          mutations.forEach(function( mutation ) {
            var newNodes = mutation.addedNodes; // DOM NodeList
            if( newNodes !== null ) { // If there are new nodes added
                var $nodes = $( newNodes ); // jQuery set
                $nodes.each(function() {
                    var $node = $( this );
                    if( $node.hasClass( "zoomtracker" ) ) {
                        //console.log("zoomtracker");
                        jQuery($node).draggable({revert:true,revertDuration:0,cursor: "move",refreshPositions:true,
                            cursorAt: { top: 0, left: 0 },
                            helper: function( ev ) {return $( "<img src='/static/drag_cursor.png'>" );}});
                    }
                });
            }
          });
        });
        var config = {attributes: true,childList: true,characterData: true};
        observer.observe(target, config);
        // Enable the popover
        var option={'trigger':'hover','html':true};
        $('div.subimg').popover(option);
        $('.ddets').click(function(e){
            e.stopPropagation();
//            var url="/objectdetails/"+$(e.target).closest('td').find('img').prop('id').substr(1);
//            var win = window.open(url, '_blank');
            var url="/objectdetails/"+$(e.target).closest('td').find('img').prop('id').substr(1)+"?w="+($(window).width()-400)+"&h="+($(window).height()-40)+"&ajax=1";
            var options={};
            $("#PopupDetails .modal-content").html("Loading...");

            $('#PopupDetails .modal-lg').css('width',$(window).width()-40);
            $('#PopupDetails').modal(options);
            $("#PopupDetails .modal-content").load(url);
            });
$('#PopupDetails').on('hidden.bs.modal', function (e) {
    $("#PopupDetails .modal-content").html("CLEAN");
    $(".zoomContainer").remove();
});

jQuery('.SpanSelectAll').click(SelectAll);
$(document).scrollTop(RightPanelScrollPosAfterLoad);
RightPanelScrollPosAfterLoad=0;
}  //PostAddImages

function SelectAll(e){
  if (!e.shiftKey)
      jQuery('.imgtab td:not(.linestart)').addClass('ui-selected');
  else
      jQuery('.imgtab td:not(.linestart)').removeClass('ui-selected');
  UpdateSelectedCounter();
}

function ClearAllFilterCriteria(){
    ClearCoord();
    ClearDates();
    ClearTimes();
    ClearSamples();
    ClearInstrum();
    ClearDepths();
    ClearAnnotFree();
    LoadRightPane();
}
function ClearAnnotFree(){
  $( "#filt_freenumst,#filt_freenumend,#filt_freetxtval" ).val("");
  $( "#filt_annot,#filt_freenum,#filt_freetxt" ).val(null).trigger("change");
}

jQuery(window).bind('beforeunload', function(){
    if(Object.keys(PendingChanges).length>0)
      return "Some changes are pending, if you continue they will be discarded !\n\nWould you still like to continue ?"
});

function GotoWithFilter(Target){
  LoadRightPane(Target);
}
function AdvancedAnnot(){
  if($('#projid').val()==null) return;
  $("#PopupDetails .modal-content").html("Loading...");
  $('#PopupDetails .modal-lg').css('width',800);
  $('#PopupDetails').modal({});

  var url="/search/annot/"+$('#projid').val();
  $("#PopupDetails .modal-content").load(url,function () {
    var lst="";
    var sampleid=$('#filt_annot');
    lst=$.map(sampleid.find('option:selected'), function (element) { return $(element).val() }).join(', ');
    $('#txtlstsample').val(lst);
    SampleTxtToCB();

  });

}

</script>
        <div id="column-right" >
            RIGHT
            {% if right=='dodefault' %}
                <script>
                $(document).ready(function() {
                        LoadRightPane();
                       }); // Ready
                 </script>
                Loading ....
            {% else %}
                {{ right|safe }}
            {% endif %}
		</div>
    </div> {# Container #}



<div id="PopupDetails" class="modal " tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      ...
    </div>
  </div>
</div>

{% endblock %}